<template>
  <el-dialog
    class="custom-dialog"
    v-model="dialogVisible"
    align-center
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    title="视频回放"
    width="800px"
    @open="handleOpen"
    @close="handleClose"
  >
    <div class="detail">
      <div class="info">
        <el-row :gutter="20">
          <el-col :span="24">
            <span class="label">设备名称:</span>
            <span class="value">{{ detail.nickName }}</span>
          </el-col>
        </el-row>
      </div>

      <div class="dialog-content">
        <div class="top">
          <el-select
            v-model="channel"
            :clearable="false"
            filterable
            placeholder="请选择频道"
          >
            <el-option
              v-for="item of channels"
              :key="item.pkid"
              :label="item.channel"
              :value="item.channel"
            >
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                "
              >
                <span>{{ generateSelectOptionLabel(item) }}</span>
                <el-text type="info">{{ item.ip }}</el-text>
              </div>
            </el-option>
          </el-select>

          <el-date-picker
            v-model="startTime"
            type="datetime"
            placeholder="请选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />

          <el-button
            :disabled="playButtonDisabled"
            type="primary"
            @click="handlePlay"
          >
            播放
          </el-button>
        </div>

        <div id="playback-video" class="video-wrapper">
          <img v-if="url" style="width: 100%; height: 100%" :src="azImg2" />
          <div class="video-no" v-else>
            <div class="img"></div>
            <span>请先选择频道和时间范围</span>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { computed, ref } from 'vue'
import Player from 'xgplayer'
// import Mp4Plugin from 'xgplayer-mp4'

import azImg2 from '@/assets/imgs/manager/azImg2.png'
import {
  fetchStorageDeviceChannels,
  fetchStorageDevicePlayback,
} from '@/api/manager/dataManage/deviceManage'

let player = null

const props = defineProps({
  detail: {
    type: Object,
    default: () => {},
  },
})

const emit = defineEmits(['close'])

const dialogVisible = ref(false)

const channels = ref([])

const url = ref('')

const channel = ref('')

const startTime = ref([])

const generateSelectOptionLabel = (item) => {
  let label = item.channel
  if (item.nickName) {
    label += `(${item.nickName})`
  }
  return label
}

const handlePlay = () => {
  fetchStorageDevicePlayback({
    pkid: props.detail.pkid,
    channel: channel.value,
    startTime: startTime.value,
    endTime: dayjs(startTime.value)
      .add(5, 'minute')
      .format('YYYY-MM-DD HH:mm:ss'),
  }).then((res) => {
    if (res.success) {
      url.value = `${window.VIDEO_BASE_URL}/cvr/${res.data}`
      // url.value = `/video/cvr/${res.data}`
      console.log('播放地址', url.value)
      if (!player) {
        initPlayer()
      } else {
        // player.switchURL(url.value)
        try {
          player.destroy()
        } catch (error) {
          console.error('player destroy failed:', error)
        }
        player = null
        initPlayer()
      }
    } else {
      ElMessage.error(res.message || '获取播放地址失败')
    }
  })
}

const initPlayer = () => {
  player = new Player({
    id: 'playback-video',
    url: url.value,
    // width: '100%',
    // height: '420px',
    autoplay: true,
    autoplayMuted: true,
    loop: true,
    fluid: true,
    fitVideoSize: 'auto',
    // plugins: [Mp4Plugin],
  })
  player.on('loadstart', () => {
    console.log('player loadstart')
  })
  player.on('loadeddata', () => {
    console.log('player loadeddata')
  })
  player.on('error', (error) => {
    console.warn('player error', error)
  })
}

const handleOpen = () => {
  fetchStorageDeviceChannels(props.detail.pkid).then((res) => {
    if (res.success) {
      channels.value = res.data
    } else {
      ElMessage.error(res.message || '获取频道错误')
    }
  })
}

const handleClose = () => {
  dialogVisible.value = false
  channel.value = ''
  startTime.value = ''
  url.value = ''
  if (player) {
    try {
      player.destroy()
    } catch (error) {
      console.error('player destroy failed:', error)
    }
    player = null
  }
  emit('close')
}

const playButtonDisabled = computed(
  () => !channel.value || !startTime.value || !dayjs(startTime.value).isValid(),
)

defineExpose({ dialogVisible })
</script>
<style lang="scss" scoped>
.detail {
  width: 100%;
  display: flex;
  flex-direction: column;

  .info {
    width: 100%;
    height: 36px;
    background: rgba(117, 117, 117, 0.05);
    border-radius: 4px;
    margin-bottom: 20px;
    :deep(.el-row) {
      height: 100%;
      display: flex;
      align-items: center;
    }
    .label {
      font-size: 14px;
      line-height: 16px;
      font-weight: 400;
      color: #333333;
      display: inline-block;
      margin-right: 10px;
      text-align: right;
      width: 80px;
    }
    .value {
      display: inline-block;
      font-size: 14px;
      line-height: 16px;
      font-weight: 400;
      color: #757575;
      .svg-icon {
        width: 15px;
        height: 14px;
        margin: 0px 0 0 10px;
        cursor: pointer;
      }
    }
  }

  .dialog-content {
    display: flex;
    flex-direction: column;

    .top {
      width: 100%;
      display: inline-flex;
      align-items: center;
      column-gap: 20px;

      .el-select {
        width: 160px;
      }
    }
  }

  .video-wrapper {
    width: 100%;
    height: 420px;
    .video-no {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      .img {
        width: 450px;
        height: 280px;
        background: url('@/assets/imgs/manager/no-video.png') no-repeat;
        background-size: 100% 100%;
      }
      span {
        position: absolute;
        top: 280px;
        font-size: 14px;
        font-weight: 400;
        color: #757575;
      }
    }
  }
}
</style>
